package com.woniu.zsd.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.zsd.common.util.RedisKey;
import com.woniu.zsd.common.web.PageInfo;
import com.woniu.zsd.platform.dao.AccountRoleMapper;
import com.woniu.zsd.platform.dao.ResourceMapper;
import com.woniu.zsd.platform.dao.RoleMapper;
import com.woniu.zsd.platform.dto.AccountDto;
import com.woniu.zsd.platform.dto.MenuDto;
import com.woniu.zsd.platform.model.Account;
import com.woniu.zsd.platform.dao.AccountMapper;
import com.woniu.zsd.platform.model.AccountRole;
import com.woniu.zsd.platform.model.Role;
import com.woniu.zsd.platform.param.AccountParam;
import com.woniu.zsd.platform.param.AddAccountParam;
import com.woniu.zsd.platform.param.ChatParam;
import com.woniu.zsd.platform.param.SelectAccountParam;
import com.woniu.zsd.platform.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.zsd.platform.service.MqttGateway;
import org.aspectj.weaver.ast.Var;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangtao
 * @since 2025年02月18日
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Resource
    private AccountRoleMapper accountRoleMapper;
    @Resource
    private RoleMapper   roleMapper;
    @Resource
    private RedisTemplate<String, Object> redisObjectTemplate;
    @Resource
    private ResourceMapper resourceMapper;
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    MqttGateway mqttGateway;
    //TODO: 实现登录逻辑
    @Override
    public AccountDto AccountLogin(AccountParam param) throws Exception {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", param.getPhone());
        Account account = accountMapper.selectOne(wrapper);
        if (account == null) {
            throw new Exception("账号不存在");
        }
        if (account.getStatus() == 0) {
            throw new Exception("账号已被禁用");
        }
        if (!account.getPassword().equals(param.getPassword())) {
            throw new Exception("密码错误");
        }
        account.setLastLoginTime(LocalDateTime.now());
        accountMapper.updateById(account);

        AccountDto accountDto = accountMapper.selectAccountDtoByAccountId(account.getAccountId());
        //添加菜单
        ArrayList<MenuDto> menuList = new ArrayList<>();
        List<com.woniu.zsd.platform.model.Resource> menus = resourceMapper.selectResourceByParentId(0, accountDto.getAccountId());
        for (com.woniu.zsd.platform.model.Resource menu : menus) {
            MenuDto menuDto = BeanUtil.toBean(menu, MenuDto.class);
            findChildMenu(menuDto,accountDto.getAccountId());
            menuList.add(menuDto);
        }
        //将用户的菜单保存到redis里面
        redisObjectTemplate.opsForValue().set(RedisKey.USER_MENU_LIST2(accountDto.getAccountId()),menuList);
        //查询当前管理员拥有的所有菜单和权限（按钮）
        List<String> resource = resourceMapper.selectResourceByAccountId(accountDto.getAccountId());
        redisObjectTemplate.opsForValue().set(RedisKey.USER_PERMISSION_LIST2(accountDto.getAccountId()),resource);
        return accountDto;
    }
    //递归查询子菜单
    public void findChildMenu(MenuDto menuDto,Integer accountId) throws Exception {
        List<com.woniu.zsd.platform.model.Resource> menus = resourceMapper.selectResourceByParentId(menuDto.getResourceId(), accountId);
        for (com.woniu.zsd.platform.model.Resource menu : menus) {
            MenuDto childrenMenuDto = BeanUtil.toBean(menu, MenuDto.class);
            menuDto.getChildren().add(childrenMenuDto);
            findChildMenu(childrenMenuDto,accountId);
        }
    }

    @Override
    public void AddAccount(AddAccountParam param) throws Exception {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", param.getPhone());
        Account account = accountMapper.selectOne(wrapper);
        if (account != null) {
            throw new RuntimeException("手机号已存在");
        }
        //新增后台人员
        Account account1 = new Account();
        account1.setPhone(param.getPhone());
        account1.setPassword(param.getPassword());
        account1.setAccountName(param.getAccountName());
        account1.setStatus(0);
        account1.setPassword("123456");
        accountMapper.insert(account1);
    }

    @Override
    public PageInfo selectAccount(SelectAccountParam param) throws Exception {
        //TODO: 查询所有后台人员
        //分页查询
        Page<AccountDto> dtoPage = new Page<>(param.getPageNum(), param.getPageSize());
        accountMapper.selectAccount(dtoPage,param.getAccountName());
        PageInfo pageInfo = new PageInfo(dtoPage);
        return pageInfo;
    }

    @Override
    public void chat(ChatParam param) {
        //redis存储单一用户的聊天记录
        param.setTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
        //客服发送消息
        param.setSenderType("service");
        redisTemplate.opsForZSet().add(RedisKey.chatHistory(param.getRecyclingOrderNum()),JSONUtil.toJsonStr(param),System.currentTimeMillis());

        // 假设客服与用户的聊天主题为 "chat/user"
        mqttGateway.sendToMqtt("chat/"+param.getRecyclingOrderNum(), JSONUtil.toJsonStr(param));
    }

    @Override
    public List<String> selectAccountNoRole() throws Exception {
        return accountMapper.selectAccountNoRole();
    }

    @Override
    public void chatWithCustomer(ChatParam param) {
        //redis存储单一用户的聊天记录
        param.setTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
        param.setSenderType("customerService");
        redisTemplate.opsForZSet().add(RedisKey.chatWithCustomerServiceHistory(param.getUserId()),JSONUtil.toJsonStr(param),System.currentTimeMillis());
        // 假设客服与用户的聊天主题为 "chat/user"
        mqttGateway.sendToMqtt("chat/userid/"+param.getUserId(), JSONUtil.toJsonStr(param));
    }

    @Override
    public Set selectCustomerServiceChatHistory(Integer customerId) {
        if (redisTemplate.hasKey(RedisKey.chatWithCustomerServiceHistory(customerId))){
            Set set = redisTemplate.opsForZSet().range(RedisKey.chatWithCustomerServiceHistory(customerId), 0, -1);
            set.forEach(System.out::println);
            return set;
        }
        throw  new RuntimeException("聊天记录不存在");
    }
}
